package com.alpha.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.alpha.bom.Exam;
import com.alpha.bom.Professor;
import com.alpha.bom.RealExam;
import com.alpha.dao.ExamDao;
import com.alpha.dao.ExamResponseDao;

/**
 * Servlet implementation class ExamsResultsServlet
 */
@WebServlet("/ExamResultsServlet")
@ServletSecurity(@HttpConstraint(rolesAllowed = {"admin"}))
public class ExamResultsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(ExamResultsServlet.class.getName());
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ExamResultsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		logger.info(this.getClass().getSimpleName()+" get method started.");
		
		HttpSession session = request.getSession();
		Professor professor = null;
		String category = "";
		
		if(session.getAttribute("user") != null && session.getAttribute("user") instanceof Professor) {
			professor = (Professor) session.getAttribute("user");
		} else {
			logger.error("Professor not found.");
			response.sendRedirect("Login.jsp?message=Invalid+user.");
			return;
		}
		
		ExamDao eDao = new ExamDao();
		ExamResponseDao rDao = new ExamResponseDao();
		ArrayList<Exam> exams = null;
		
		try {
			exams = eDao.retrieveExamByProfessorId(professor.getUserId(), true);
			for(int i = 0; i < exams.size(); i++) {
				Exam exam = exams.get(i);
				((RealExam) exam).setNumberOfStudents(rDao.getNumberOfAllTakers(exam.getExamId()));
				if(((RealExam) exam).getNumberOfStudents() == 0) {
					exams.remove(exam);
					i--;
				}
			}
		} catch(Exception e) {
			logger.error(e.getMessage());
			return;
		}
		
		request.setAttribute("exams", exams);
		RequestDispatcher dispatcher = request.getRequestDispatcher("ExamResults.jsp");
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

}
